package com.zzs.esp.config;

import com.zzs.esp.components.JwtAuthenticationTokenFilter;
import com.zzs.esp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Author ZechariahZheng
 * @Date 2021/1/25 17:03
 * @Version 1.0
 * @description
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    //指定密码的加密方式
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //配置用户及其对应的角色
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }

    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){
        return new JwtAuthenticationTokenFilter();
    }

    //配置url访问权限
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.authorizeRequests() // 开启 HttpSecurity 配置
//            .antMatchers("/admin/**").hasRole("ADMIN")    // admin/** 模式URL必须具备ADMIN角色
//            .antMatchers("/user/**").access("hasAnyRole('ADMIN','USER')")    // 该模式需要ADMIN或USER角色
//            .anyRequest().authenticated()     // 用户访问其它URL都必须认证后访问（登录后访问）
//            .and().formLogin()         //开启表单登录
//            .and().formLogin().loginProcessingUrl("/login").permitAll() //开启表单登录并配置登录接口
//            .and().csrf().disable(); // 关闭csrf(跨域请求伪造)
        http.csrf().disable()   //关闭csrf(跨域请求伪造)
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)     //基于token,不需要session
            .and().authorizeRequests()
            .antMatchers(HttpMethod.GET, // 允许对于网站静态资源的无授权访问
                "/",
                "/*.html",
                "/favicon.ico",
                "/**/*.html",
                "/**/*.css",
                "/**/*.js",
                "/swagger-resources/**",
                "/v2/api-docs/**"
            ).permitAll()
            .antMatchers("/user/login", "/user/register", "/admin/login").permitAll()     //对登录注册要允许匿名访问
            .anyRequest().authenticated();       // 除上面外的所有请求全部需要鉴权认证
        // 禁用缓存
        http.headers().cacheControl();
        // 添加JWT filter
        http.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}
